package com.simple.util.common;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

public class Utils {
    /** The Constant LOG. */
    private static final Logger LOG = Logger.getLogger(Utils.class);

    /**
     * Compare length of input String and input criteria.
     * 
     * @param sEntry
     *            Input String to compare
     * @param iLength
     *            Target length
     * @return If sEntry is null or shorter than iLength, return false; otherwise, return true
     */
    public static boolean checkLength(final String sEntry, final int iLength) {
        boolean result = true;
        if (null == sEntry) {
            result = false;
        } else {
            if (sEntry.length() < iLength) {
                result = false;
            }
        }
        return result;
    }


    /**
     * remove String spaces.
     * 
     * @param sString
     *            the s string
     * @return remove spaces of String
     */
    public static String removeNull(final String sString) {
        String s = "";
        if (null != sString) {
            s = sString;
        }
        return s;
    }

    /**
     * remove String spaces.
     * 
     * @param sString
     *            the s string
     * @return remove spaces of String
     */
    public static String removeNullTrim(final String sString) {
        String s = "";
        if (null != sString) {
            s = sString.trim();
        }
        return s;
    }

    /**
     * convert String to int.
     * 
     * @param sValue
     *            sValue
     * @return int
     */
    public static int parseInt(final String sValue) {
        int i;
        try {
            i = Integer.parseInt(sValue);
        } catch (NumberFormatException e) {
            i = 0;
        }
        return i;
    }


    /**
     * Convert amount/units/percentage fields to double.
     * 
     * @param sEntry
     *            the s entry
     * @return the double
     */
    public static double convertToDouble(final String sEntry) {
        int iSign, iLength;
        boolean bNegative = false;
        double dValue;
        double result = 0;

        if (null != sEntry) {
            String sNoSignNum = sEntry;

            iLength = sEntry.trim().length();
            // Quit if empty string is passed
            if (null == sEntry || iLength == 0) {
                result = 0;
            } else {
                try {
                    iSign = sEntry.indexOf('-') + 1;

                    // Check for negative sign
                    if (iSign > 0) {
                        bNegative = true;
                        sNoSignNum = sEntry.replace('-', ' ');
                    }

                    dValue = Double.parseDouble(sNoSignNum);

                    if (bNegative) {
                        result = (dValue * -1);
                    } else {
                        result = dValue;
                    }
                } catch (NumberFormatException e) {
                    result = 0;
                }
            }
        }
        return result;
    }


    /**
     * According to input Object, Returns the Object class name.
     * 
     * @param o
     *            the o
     * @return Class Name
     */
    public static String getClassName(final Object o) {
        String result = "";
        if (null != o) {
            final String asClass = o.getClass().getName();
            final StringTokenizer sToken = new StringTokenizer(asClass, ".");
            String asToken = asClass;
            while (sToken.hasMoreElements()) {
                asToken = sToken.nextToken();
            }
            result = asToken;
        }
        return result;
    }

    

    /**
     * remove String CR("\r","\n").
     * 
     * @param s
     *            the s
     * @return remove CR of String
     */
    public static String removeCR(final String s) {
        String result = "";
        if (null != s && !"".equals(s)) {
            final String s1 = s.replaceAll("\r", "");
            result = s1.replaceAll("\n", "");
        }
        return result;
    }

    /**
     * remove String CR("\r","
     * <p>
     * ","\n").
     * 
     * @param s
     *            the s
     * @return remove CR of String
     */
    public static String replaceCR(final String s) {
        String result = "";
        if (null != s && !"".equals(s)) {
            final String s1 = s.replaceAll("\r", "<p>");
            result = s1.replaceAll("\n", "");
        }
        return result;
    }

    // add by 020110
    /**
     * According to input filePath and content of Create file.
     * 
     * @param filePath
     *            file path
     * @param content
     *            file content
     * @throws IOException
     *             Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.
     */
    public static void createFile(final String filePath, final String content) throws IOException {
        FileWriter fw = null;
        try {
            final File file = new File(filePath);
            if (file.exists()) {
                // if file exists, delete it and create new file
                if (file.delete()) {
                    file.createNewFile();
                }
            } else {
                file.createNewFile();
            }
            fw = new FileWriter(file.getPath());
            fw.write(content);
        } catch (Exception e) {
            LOG.error(e.toString());
        } finally {
            if (null != fw) {
                fw.close();
            }
        }
    }

    // add end
    /**
     * According to input filePath of delete file.
     * 
     * @param filePath
     *            file path
     */
    public static void deleteFiles(final String filePath) {
        if (null != filePath) {
            final File f = new File(filePath);
            final File[] fs = f.listFiles();
            if (null != fs) {
                for (int i = 0; i < fs.length; i++) {
                    fs[i].delete();
                }
            }
        }
    }

    /**
     * According to input filePath of check the file exist.
     * 
     * @param filename
     *            the filename
     * @return If check the file exist, return true; otherwise, return false
     */
    public static boolean checkFileExist(final String filename) {
        File f = null;
        if (null != filename) {
            f = new File(filename);
        }
        return (null == f ? false : f.exists());
    }
    
    /**
     * String to BigDecimal
     * 
     * @param decimal
     * @param dateString2
     * @return BigDecimal
     */
    public static BigDecimal formatToBigDecimal(final String str,final int decimal) {
        BigDecimal rtn = null;
        if (str != null && !str.trim().isEmpty() && !"0".equals(str.trim())) {
            if (str.indexOf('.') >= 0) {
                rtn = new BigDecimal(str.trim());
            } else {
                final String numStr = (str.substring(0, str.length() - decimal) + "." + str.substring(
                                str.length() - decimal, str.length())).trim();
                rtn = new BigDecimal(numStr);
            }
        } 
        
        return rtn;
    }
    
    public static File openFile(final String fileName){
        File f = null;
        if(fileName!=null){
            final String fName = fileName.trim();
            final String pre = "classpath:";
            if(fName.indexOf(pre)==0){
                final String className = fName.substring(pre.length());
                String path = className.replace('.', '/');
                if(path.indexOf('/')==0){
                    path = path.substring(1);
                }
                final int extPost = path.lastIndexOf('/');
                path = path.substring(0, extPost)+'.'+path.substring(extPost+1);
                final URL url = Thread.currentThread().getContextClassLoader().getResource(path);
                if(url!=null){
                    f = new File(url.getFile());
                }
            }else{
                f = new File(fName);
                if(!f.exists()){
                    f = null;
                }
            }
        }
        return f;
    }
    
    public static <T>T[] copyArray(final T[] srcArray) {
        final T[] rtnArray;
        if(srcArray == null){
            rtnArray = null;
        }else{
            rtnArray = Arrays.copyOf(srcArray, srcArray.length);
        }
        return rtnArray;
    }
    
    public static String[] copyArray(final String[] srcArray) {
        final String[] rtnArray;
        if(srcArray == null){
            rtnArray = null;
        }else{
            rtnArray = Arrays.copyOf(srcArray, srcArray.length);
        }
        return rtnArray;
    }

    public static byte[] copyArray(final byte[] srcArray) {
        final byte[] rtnArray;
        if(srcArray == null){
            rtnArray = null;
        }else{
            rtnArray = Arrays.copyOf(srcArray, srcArray.length);
        }
        return rtnArray;
    }
    
    /**
     * check whether str contains string (str split by ";")
     * @param string
     * @param str
     * @return
     */
    public static boolean checkStringContainsStr(final String string, final String str){
        return checkStringContainsStr(string,str,";");
    }
    
    /**
     * check whether str contains string (str split by regex)
     * @param string
     * @param str
     * @param regex
     * @return
     */
    public static boolean checkStringContainsStr(final String string, final String str, final String regex){
        boolean temp = false;
        if(!StringUtil.isNull(string) && !StringUtil.isNull(str)){
            final List<String> dataList = StringUtil.splitByTrim(str, regex);
            for(String data : dataList){
                if(string.equals(data)){
                    temp = true;
                    break;
                }
            }
        }
        return temp;
    }
    
    /**
     * copy list.
     * 
     * @param originalList
     *            the original list
     * @return a copy list of all originalList iterms
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static List copyList(final List originalList) {
        final List rtnList = new ArrayList();
        if (null != originalList) {
            rtnList.addAll(originalList);
        }
        return rtnList;
    }

}
